package com;


import java.io.File;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;



import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.admin.User;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.util.db.DBSessionGenerator;



public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected  final long DAILY_MILLS = 24 * 60 * 60 * 1000;
	
	
	protected  SessionMap<String, Object> session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	
	protected String message;
	// 1-Success 2-fail
	protected int isSuccess;
	
	protected int dcqx;
	protected Gson gson = new Gson();
	


	 /**
     * 灏嗘煡璇㈢粨鏋滈泦鍝嶅簲鍥炶鍥�
     * @param list 缁撴灉闆�
     * @param <T> 瀹炰綋瀵硅薄绫诲瀷

     * @return  json
     */
    protected <T> String ajaxJson(List<T> list)
    {
        String strs = "{\"results\":" + list.size() + ",\"data\":" + gson.toJson(list) + ",\"success\":true}";
        //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJson(List<T> list,int type)
    {
        String strs = "{\"results\":" + type + ",\"data\":" + gson.toJson(list) + ",\"success\":true}";
        //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJsonTable(List<T> list)
    {
        String strs = gson.toJson(list);
        System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    
    protected  String getOrderIdByUUId(int userid) {
        int machineId = 1;//最大支持1-9个集群机器部署
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {//有可能是负数
            hashCodeV = - hashCodeV;
        }
//         0 代表前面补充0     
//         4 代表长度为4     
//         d 代表参数为正数型
        return  machineId+userid+ String.format("%015d", hashCodeV);
    }
    protected  boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
   }
    
    
    protected <T> String ajaxJsontocj(List<T> list)
    {
        String strs = gson.toJson(list);
        //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJson(String str)
    {
    	String strs = "{\"code\":0,\"msg\":\""+str+"\",\"data\":\"\"}";
		 //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJson(String str,int code)
    {
    	String strs = "{\"code\":"+code+",\"msg\":\""+str+"\",\"data\":\"\"}";
		 System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJsontable(List<T> list)
    {
    	String strs = "{\"code\":0,\"msg\":\"\",\"count\": " + list.size() + ",\"data\":" + gson.toJson(list) + "}";
		 //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJsontablefy(String string,List<LinkedHashMap<String, String>> list)
    {
    	String strs = "{\"code\":0,\"msg\":\"\",\"count\": " + string + ",\"data\":" + gson.toJson(list) + "}";
		// System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJsontablefybycalss(String string,List<T> list)
    {
    	String strs = "{\"code\":0,\"msg\":\"\",\"count\": " + string + ",\"data\":" + gson.toJson(list) + "}";
		 //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
    
    protected <T> String ajaxJsontableclassfy(String string,List<T> list)
    {
    	String strs = "{\"code\":0,\"msg\":\"\",\"count\": " + string + ",\"data\":" + gson.toJson(list) + "}";
		 //System.err.println(strs);
        jsonWriter(strs);
        return strs;
    }
	/**
     * 灏唈son鏁版嵁鍐欏叆姝ゆ鍝嶅簲娴佷腑
     * @param str json鏁版嵁
     */
    protected  void jsonWriter(String str)
    {
        Writer writer = null;
        try
        {
            try
            {
            	ServletActionContext.getResponse().setHeader("Content-type", "text/html;charset=UTF-8");  
            	ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
                writer = ServletActionContext.getResponse().getWriter();
                writer.write(str);
            }
            finally
            {
                writer.flush();   // 寮哄埗杈撳嚭鎵�鏈夊唴瀹�
                writer.close();   // 鍏抽棴
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
	
   
    
   
	
    private  final int CPUTIME = 500;  
    
    private  final int PERCENT = 100;  
      
    private  final int FAULTLENGTH = 10;  
    protected  List<String> getDisk()  
    {  
        // 鎿嶄綔绯荤粺  
        List<String> list = new ArrayList<String>();  
        for (char c = 'A'; c <= 'Z'; c++)  
        {  
            String dirName = c + ":/";  
            File win = new File(dirName);  
            if (win.exists())  
            {  
                long total = (long)win.getTotalSpace();  
                long free = (long)win.getFreeSpace();  
                Double compare = (Double)(1 - free * 1.0 / total) * 100;  
                String str = compare.intValue()+"" ;  
                list.add(str);  
            }  
        }  
        return list;  
    }  
      
    //鑾峰緱cpu浣跨敤鐜�  
    protected  String getCpuRatioForWindows()  
    {  
        try  
        {  
            String procCmd =  
                System.getenv("windir")  
                    + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
            // 鍙栬繘绋嬩俊鎭�  
            long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));  
            Thread.sleep(CPUTIME);  
            long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));  
            if (c0 != null && c1 != null)  
            {  
                long idletime = c1[0] - c0[0];  
                long busytime = c1[1] - c0[1];  
                return  Double.valueOf(PERCENT * (busytime) * 1.0 / (busytime + idletime)).intValue() +"";  
            }  
            else  
            {  
                return  0+"";  
            }  
        }  
        catch (Exception ex)  
        {  
            ex.printStackTrace();  
            return  0 + "";  
        }  
    }  
    
    
    
    
    private  long[] readCpu(final Process proc)  
    {  
        long[] retn = new long[2];  
        try  
        {  
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();  
            if (line == null || line.length() < FAULTLENGTH)  
            {  
                return null;  
            }  
            int capidx = line.indexOf("Caption");  
            int cmdidx = line.indexOf("CommandLine");  
            int rocidx = line.indexOf("ReadOperationCount");  
            int umtidx = line.indexOf("UserModeTime");  
            int kmtidx = line.indexOf("KernelModeTime");  
            int wocidx = line.indexOf("WriteOperationCount");  
            long idletime = 0;  
            long kneltime = 0;  
            long usertime = 0;  
            while ((line = input.readLine()) != null)  
            {  
                if (line.length() < wocidx)  
                {  
                    continue;  
                }  
                // 瀛楁鍑虹幇椤哄簭锛欳aption,CommandLine,KernelModeTime,ReadOperationCount,  
                // ThreadCount,UserModeTime,WriteOperation  
                String caption = substring(line, capidx, cmdidx - 1).trim();  
                String cmd = substring(line, cmdidx, kmtidx - 1).trim();  
                if (cmd.indexOf("wmic.exe") >= 0)  
                {  
                    continue;  
                }  
                String s1 = substring(line, kmtidx, rocidx - 1).trim();  
                String s2 = substring(line, umtidx, wocidx - 1).trim();  
                if (caption.equals("System Idle Process") || caption.equals("System"))  
                {  
                    if (s1.length() > 0)  
                        idletime += Long.valueOf(s1).longValue();  
                    if (s2.length() > 0)  
                        idletime += Long.valueOf(s2).longValue();  
                    continue;  
                }  
                if (s1.length() > 0)  
                    kneltime += Long.valueOf(s1).longValue();  
                if (s2.length() > 0)  
                    usertime += Long.valueOf(s2).longValue();  
            }  
            retn[0] = idletime;  
            retn[1] = kneltime + usertime;  
            return retn;  
        }  
        catch (Exception ex)  
        {  
            ex.printStackTrace();  
        }  
        finally  
        {  
            try  
            {  
                proc.getInputStream().close();  
            }  
            catch (Exception e)  
            {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	protected  List<String> selectField(String nr,Map pharm) {
    	List<String> result;
    	SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		pharm.put("nr", nr);
		result=mapper.selectField(pharm);
			
		}finally{
			sqlSession.close();
		}
    	
    	return result;
    }
    
    @SuppressWarnings("rawtypes")
	protected   int daorulistxx(Map pharm) {
       	int a=0;
       	SqlSession sqlsession = getSqlSession();
    		try{
    			BaseActionMapper mapper=sqlsession.getMapper(BaseActionMapper.class);
    					
    		a=mapper.daorulistxx(pharm);
    			
    		}finally{
    			sqlsession.close();
    		}
       	
       	return a;
       }
    @SuppressWarnings("rawtypes")
	protected   int daorulistxxbystring(Map pharm) {
       	int a=0;
       	SqlSession sqlsession = getSqlSession();
    		try{
    			BaseActionMapper mapper=sqlsession.getMapper(BaseActionMapper.class);
    					
    		a=mapper.daorulistxxbystring(pharm);
    			
    		}finally{
    			sqlsession.close();
    		}
       	
       	return a;
       }
   
    
	@SuppressWarnings("rawtypes")
	protected int updatetablebykey(Map pharm) {
    	int result=0;
    	SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		result=mapper.updatetable(pharm);
			
		}finally{
			sqlSession.close();
		}
    	
    	return result;
    }
	
	@SuppressWarnings({ "rawtypes" })
	protected void createlstbale(Map map) {
		SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.createlstbale(map);
			
		}finally{
			sqlSession.close();
		}
		
	}
	
	
	@SuppressWarnings({ "rawtypes" })
	protected void deletelstable(Map map) {
		SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.deletelstable(map);
			
		}finally{
			sqlSession.close();
		}
		
	}
	@SuppressWarnings({ "rawtypes" })
	protected void drouplstable(Map map) {
		SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.drouplstable(map);
			
		}finally{
			sqlSession.close();
		}
		
	}
	
	@SuppressWarnings("rawtypes")
	protected int updatetablebywhere(Map pharm) {
    	int result=0;
    	SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		result=mapper.updatetablebywhere(pharm);
			
		}finally{
			sqlSession.close();
		}
    	
    	return result;
    }
	
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected void updatelog(Map map) {
		map.put("table", "\"Loginformation\"");
		
		updatetablebywhere(map);
	}
	
	
	
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void savelog(String msg) {
			 Map map=new HashMap();
			map.put("Value", msg);
			String nr="\"Result\"="+"'"+msg+"'";
			map.put("nr", nr);
			User loginuser = (User)session.get(Constants.USER);
			String where="\"Logid\"=(select \"Logid\" from \"Loginformation\" where \"Createuserid\"="+loginuser.getUserid()+"    order by \"Logid\" desc LIMIT 1)";
			map.put("where", where);
			updatelog(map);
		
	}
	
	
	@SuppressWarnings("rawtypes")
	protected  List<LinkedHashMap<String, String>> selecttable(Map pharm) {
		List<LinkedHashMap<String, String>> result;
    	SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		result=mapper.selecttable(pharm);
			
		}finally{
			sqlSession.close();
		}
    	
    	return result;
    }
	
	
	@SuppressWarnings("rawtypes")
	protected  List<LinkedHashMap<String, String>> selecttableall(Map pharm) {
		List<LinkedHashMap<String, String>> result;
    	SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		result=mapper.selecttableall(pharm);
			
		}finally{
			sqlSession.close();
		}
    	
    	return result;
    }
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected  String runsql(String sql) {
		
		SqlSession sqlSession = getSqlSession();
		String message="";
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		 Map map=new HashMap();
		 map.put("sql",sql);
		 mapper.runsql(map);
			
		}catch(Exception  e) {
			message="系统错误"+e.getMessage().toString();
		}
		finally{
			  
			sqlSession.close();
		}
		return message;
		
	}
	
	
	
	@SuppressWarnings("rawtypes")
	protected  void deletetable(Map pharm) {
		SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.deletetable(pharm);
			
		}finally{
			sqlSession.close();
		}
    }
	
	@SuppressWarnings("rawtypes")
	protected  String inserttable(Map pharm) {
		SqlSession sqlSession = getSqlSession();
		String message="";
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.inserttable(pharm);
			
		}catch(Exception  e) {
			message="系统错误,导入失败"+e.getMessage().toString();
		}
		finally{
			  
			sqlSession.close();
		}
		return message;
    }
    
	@SuppressWarnings("rawtypes")
	protected  void insertlsb(Map pharm) {
		SqlSession sqlSession = getSqlSession();
		try{
		BaseActionMapper mapper=sqlSession.getMapper(BaseActionMapper.class);
		mapper.insertlsb(pharm);
			
		}finally{
			sqlSession.close();
		}
    }
	
	protected String getvalue(Cell cell) {
		String cellValue = "";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
            case NUMERIC: // 数字
                cellValue = cell.getNumericCellValue() + "";
                NumberFormat nf = NumberFormat.getInstance();
                cellValue=nf.format(cell.getNumericCellValue()).replace(",", "");
                break;
            case STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA: // 公式
                cellValue = cell.getCellFormula() + "";
                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
            }
			
		}
        return cellValue;
        }
	
	@SuppressWarnings({ "rawtypes", "unchecked" })//新增方法
	protected  List<LinkedHashMap<String, String>> getlist(Map params){
		String where="1=1";
		String fy="";
		Iterator<String> iter = params.keySet().iterator();
		while(iter.hasNext()){
			   String key=iter.next();
			   String value =params.get(key).toString();
             if(key.equals("fybetween")) {
				   
            	   fy+=" and "+value;
			   }else  if(key.equals("like")||key.equals("between")) {
				   
            	 where+=" and "+value;
			   }
             else  if(!key.equals("nr")&&!key.equals("table")&&!key.equals("px")&&!key.equals("group")&&!key.equals("jointable")){
				   
				   where+=" and \""+key+"\"='"+value+"'";
			   }
		 }
		
		Map map=new HashMap();
		map.put("table", params.get("table"));
		map.put("px", params.get("px"));
		map.put("group", params.get("group"));
		map.put("where", where);
		map.put("fy", fy);
		map.put("jointable", params.get("jointable"));
		map.putAll(params);
		List<LinkedHashMap<String, String>> com=selecttable(map);
		return com;
	}
	
    
    private  String substring(String src, int start_idx, int end_idx)  
    {  
        byte[] b = src.getBytes();  
        String tgt = "";  
        for (int i = start_idx; i <= end_idx; i++)  
        {  
            tgt += (char)b[i];  
        }  
        return tgt;
    }
	
	public void setSession(Map<String, Object> session) {
		this.session = (SessionMap<String, Object>)session;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	protected String trim(String s) {
		if (s == null) return s;
		return s.trim();
	}
	
	protected boolean isEmpty(String s) {
		return s == null|| s.isEmpty();
	}
	
	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	
	@SuppressWarnings("rawtypes")
	protected boolean isListEmpty(List l) {
		return l == null || l.size() == 0;
	}
	
	protected boolean isNumber(String s) {
		if (isEmpty(s)) return false;
		return s.matches("^\\d+$");
	}
	
	protected int toInt(String s) {
		if (!isNumber(s)) return 0;
		return Integer.parseInt(s);
	}
	
	protected boolean isEquals(String s1, String s2) {
		if (s1 == null) return false;
		return s1.equals(s2);
	}
	
	protected String lower(String s) {
		return s == null ? "" : s.toLowerCase();
	}
	
	protected String upper(String s) {
		return s == null ? "" : s.toUpperCase();
	}
	
	
   
	
	
	
	protected   SqlSession getSqlSession() {
		return DBSessionGenerator.getSqlSession();
	}
	
	protected SqlSession getSqlSession(boolean autoCommit) {
		return DBSessionGenerator.getSqlSession(autoCommit);
	}
	
	protected SqlSession getSqlSession(String list) {
		return DBSessionGenerator.getSqlSession(list);
	}
	
	protected SqlSession getSqlSession(String list,boolean autoCommit) {
		return DBSessionGenerator.getSqlSession(list,autoCommit);
	}
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public int getDcqx() {
		return dcqx;
	}

	public void setDcqx(int dcqx) {
		this.dcqx = dcqx;
	}

	public int getIsSuccess() {
		return isSuccess;
	}

	public void setIsSuccess(int isSuccess) {
		this.isSuccess = isSuccess;
	}

}